package com.zw.rpc.client;

import com.zw.rpc.codec.Decoder;
import com.zw.rpc.codec.Encoder;
import com.zw.rpc.common.utils.ReflectionUtils;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Proxy;

/**
 * @author zw
 */
@Data
@NoArgsConstructor
public class RpcClient {

    private RpcClientConfig config;

    private Encoder encoder;

    private Decoder decoder;

    private TransportSelector selector;

    public RpcClient(RpcClientConfig config) {
        this.config = config;
        this.encoder = ReflectionUtils.newInstance(this.config.getEncoder());
        this.decoder = ReflectionUtils.newInstance(this.config.getDecoder());
        this.selector = ReflectionUtils.newInstance(this.config.getSelector());

        this.selector.init(this.config.getPeers(),this.config.getConnectCount(),this.config.getTransportClient());
    }

    public <T> T getProxy(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{clazz},new RemoteInvoker(clazz,encoder,decoder,selector));
    }
}
